package zmee.pur.src.opplugin;

import com.alibaba.fastjson.JSONArray;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.entity.ILocaleString;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.AfterOperationArgs;
import kd.bos.exception.KDBizException;
import kd.bos.fileservice.FileItem;
import kd.bos.fileservice.FileService;
import kd.bos.fileservice.FileServiceFactory;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.service.attachment.FilePathService;
import kd.bos.servicehelper.AttDto;
import kd.bos.servicehelper.AttachmentDto;
import kd.bos.servicehelper.AttachmentServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;
import kd.bos.trace.core.TraceKeys;
import kd.bos.web.actions.utils.FilePathUtil;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author: zyj
 * @Date: 2023/9/5 14:53
 * @Description: 定标: 点击 推送附件至签约单 将定标单上的附件推送到签约单中
 */
public class SrcDecisionPushAnnexOpPlugin extends AbstractOperationServicePlugIn {

    private static Log logger = LogFactory.getLog(SrcDecisionPushAnnexOpPlugin.class);

    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        List<String> fieldKeys = e.getFieldKeys();
        // 寻源项目编号
        fieldKeys.add("billno");
    }

    @SneakyThrows
    @Override
    public void afterExecuteOperationTransaction(AfterOperationArgs e) {
        super.afterExecuteOperationTransaction(e);
        DynamicObject[] dataEntities = e.getDataEntities();
        for (DynamicObject dataEntity : dataEntities) {
            // 通过单据id获取定标单附件
            List<Map<String, Object>> attachments = AttachmentServiceHelper.getAttachments("src_decision", dataEntity.get("id"), "attachmentpanel");
            JSONArray jsonArray = new JSONArray();
            jsonArray.add(attachments);
            logger.info("获取定标单附件: " + jsonArray.toJSONString());
            QFilter qFilter = new QFilter("billno", QCP.equals, dataEntity.getString("billno"));

            DynamicObjectCollection query = QueryServiceHelper.query("src_contract", "id", new QFilter[]{qFilter});
            if (query == null || query.size() == 0) {
                throw new KDBizException("该寻源项目没有找到对应的签约单,推送附件失败！");
            }
            try {
                List<AttDto> newAttachments = new ArrayList<>(attachments.size());
                for (Map<String, Object> attachment : attachments) {
                    // 获取附件表中的id
                    Object attPkId = attachment.get("attPkId");
                    AttachmentDto attachmentInfoByAttPk = AttachmentServiceHelper.getAttachmentInfoByAttPk(attPkId);
                    // 获取文件的相对路径对应物理表t_bd_materialmftinfo中的FFILEID
                    String resourcePath = attachmentInfoByAttPk.getResourcePath();
                    logger.info("resourcePath = " + resourcePath);
                    // 构建附件数据传输对象
                    AttDto attDto = new AttDto();
                    // 获取文件上传人多语言文本对象
                    ILocaleString creator = (ILocaleString) attachment.get("creator");
                    String localeValue = creator.getLocaleValue_zh_CN();
                    logger.info("文件上传人 = " + localeValue);
                    DynamicObject user = QueryServiceHelper.queryOne("bos_user", "id, name", new QFilter[]{new QFilter("name", QCP.equals, localeValue)});
                    if (user != null) {
                        attDto.setCreateUserId(String.valueOf(user.get("id")));
                        logger.info("creator name = " + user.get("name"));
                    } else {
                        attDto.setCreateUserId(String.valueOf(UserServiceHelper.getCurrentUserId()));
                        logger.info("当前处理人 creatorId = " + UserServiceHelper.getCurrentUserId());
                    }
                    // 获取上传日期，由于是时间戳，要转换一下
                    Object createdate = attachment.get("createdate");
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String createdateStr = sdf.format(createdate);
                    logger.info("format date = " + createdateStr);
                    attDto.setCreateTime(createdateStr);

                    attDto.setAttKey("attachmentpanel");
                    // 由于resourcePath加密了，需要先解密 其下两个方法都可以 方法一
                    String realPath = FileServiceFactory.getAttachmentFileService().getFileServiceExt().getRealPath(resourcePath);
                    logger.info("url解密1 = " + realPath);
                    attDto.setPath(realPath);
                    // 方法二 其中 realPath 和 realPath2是同一个值
//                    FilePathService filePathService = new FilePathService();
//                    String realPath2 = filePathService.getRealPath(realPath);
//                    logger.info("url解密2 = " + realPath2);
                    attDto.setSize((long) AttachmentServiceHelper.getFileSizeByPath(attDto.getPath()));
                    newAttachments.add(attDto);
                }
                logger.info("--------");
                Map<String, Object> bindingParam = AttachmentServiceHelper.genBindingParam("src_contract", String.valueOf(query.get(0).get("id")), newAttachments);
                logger.info("获取bindingParam: " + bindingParam);
                Map<String, Object> resultMap = AttachmentServiceHelper.bindingAttachment(bindingParam);
                if (!(boolean) resultMap.get("success")) {
                    throw new KDBizException("推送附件失败！");
                }
            } catch (Exception exception) {
                exception.printStackTrace();
                logger.info("异常:" + exception.getMessage());
                if (exception instanceof Exception) {
                    throw exception;
                }
            }
        }
    }

}
